
#include "serial_device.h"

#if defined(ANDROID)
#include "android/log.h"
#include "utils/Log.h"
#ifdef LOG_TAG
#undef LOG_TAG
#endif
#define LOG_TAG "SerialControl"
#else
#include <stdio.h>
#define ALOGD printf
#endif


namespace serial {

SerialDevice::SerialDevice()
{
}

SerialDevice::SerialDevice(const char * node)
    : Device(node)
{
}

SerialDevice::~SerialDevice()
{
}

void SerialDevice::registerFsmListener(Parser::FSM* fsm, Listener* listener) 
{
    if (fsm == NULL || listener == NULL)
        return;
    mListeners[fsm] = listener;
    addFsm(fsm);
}

void SerialDevice::onRead(const char * buf, int len)
{
    ALOGD("onRead buf = %p, len = %d\n", buf, len);
    if (buf == NULL || len <= 0) {
        resetAllFsms();
        return;
    }

    const serial::Parser::FSM * fsm = NULL;
    unsigned char command[1024] = {0};
    int ret = 0;
    for (ret = parse(buf, len, command, sizeof(command), &fsm); ret >= 0; ret = parse(NULL, 0, command, sizeof(command), &fsm)) {
        if (ret == 0)
            continue;
        std::map<const Parser::FSM*, Listener*>::iterator it = mListeners.find(fsm);
        if (it == mListeners.end()) {
            ALOGD("Invalid fsm.\n");
            continue;
        }
        Listener* listener = it->second;
        if (listener != NULL)
            listener->onCommand(command, ret);
    }
}

} // namespace serial


